package com.demo.pattern.prototype;

import java.io.*;

/**
 * @author sourire
 * @version 1.0
 * @date 2020/8/20 11:45
 */
public class DeepSheep implements Cloneable,Serializable{
    //深拷贝
    private String name;
    private int age;
    private Sheep friend;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Sheep getFriend() {
        return friend;
    }

    public void setFriend(Sheep friend) {
        this.friend = friend;
    }

    public DeepSheep(String name, int age) {
        this.name = name;
        this.age = age;
    }

    //克隆方式实现深拷贝
    @Override
    protected Object clone() throws CloneNotSupportedException {
        DeepSheep sheep = null;
        sheep = (DeepSheep) super.clone();
        sheep.friend = (Sheep) sheep.friend.clone();
        return sheep;
    }

    //序列化的方式实现深拷贝
    public Object deepCopy() throws IOException {

        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;


        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            //将当前对象写入到字节输出流中
            oos.writeObject(this);

            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            //将当前
            return ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            ois.close();
            bis.close();
            oos.close();
            bos.close();
        }
    }
}
